package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class TsLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object loginAspect(ProceedingJoinPoint point,TsLogin tsLogin) throws Throwable {


        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;

        HttpServletRequest request = sra.getRequest();

        try {
            String token = request.getHeader("token");

            //判断是否需要登录
            if (tsLogin.required()) {

                //没有token 抛异常
                if (StringUtils.isEmpty(token)) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }

                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

                UserInfo userInfo = (UserInfo) this.redisTemplate.opsForValue().get(loginKey);

                //如果缓存没数据抛异常 未登录
                if (userInfo == null) {
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }
            }

            //不需要强制登录，但是需要获取用户信息
            if (!StringUtils.isEmpty(token)){
                //  如果token 不为空，从缓存中获取信息.
                UserInfo userInfo = (UserInfo) this.redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
                if (null != userInfo){
                    //  将用户信息存储到请求头中
                    AuthContextHolder.setUserId(userInfo.getId());
                    AuthContextHolder.setUsername(userInfo.getNickname());
                }
            }

            return point.proceed();
        }
        finally {
            AuthContextHolder.removeUserId();
        }

    }

}
